package com.yourgroup.common.validation;

import java.util.regex.Pattern;

/**
 * 29548
 * IntelliJ IDEA
 * 12:36
 * 星期二
 */

public class ValidationUtils {
    // 手机号正则（国内手机号规则）
    private static final Pattern PHONE_PATTERN = Pattern.compile("^1[3-9]\\d{9}$");
    // 邮箱正则
    private static final Pattern EMAIL_PATTERN = Pattern.compile("^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$");

    // 校验手机号
    public static boolean isPhone(String phone) {
        if (phone == null || phone.length() != 11) {
            return false;
        }
        return PHONE_PATTERN.matcher(phone).matches();
    }

    // 校验邮箱
    public static boolean isEmail(String email) {
        if (email == null) {
            return false;
        }
        return EMAIL_PATTERN.matcher(email).matches();
    }

    // 校验身份证号（18位）
    public static boolean isIdCard(String idCard) {
        if (idCard == null || idCard.length() != 18) {
            return false;
        }
        // 简单校验：前17位为数字，最后一位可以是数字或X/x
        if (!idCard.matches("^[0-9]{17}[0-9Xx]$")) {
            return false;
        }
        // 校验位算法（简化版）
        char[] chars = idCard.toUpperCase().toCharArray();
        int sum = 0;
        int[] weights = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2}; // 权重
        char[] checkCodes = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'}; // 校验位对应值
        for (int i = 0; i < 17; i++) {
            sum += (chars[i] - '0') * weights[i];
        }
        int checkCodeIndex = sum % 11;
        return chars[17] == checkCodes[checkCodeIndex];
    }
}

